package com.cmeduSystem.webadmin.upms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.page.PageMethod;
import com.cmeduSystem.common.sequence.wrapper.IdGeneratorWrapper;
import com.cmeduSystem.webadmin.upms.dao.SysUserPasswordHistoryMapper;
import com.cmeduSystem.webadmin.upms.model.SysUserPasswordHistory;
import com.cmeduSystem.webadmin.upms.service.SysUserPasswordHistoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service("sysUserPasswordHistoryService")
public class SysUserPasswordHistoryServiceImpl implements SysUserPasswordHistoryService {

    @Autowired
    private SysUserPasswordHistoryMapper sysUserPasswordHistoryMapper;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private IdGeneratorWrapper idGenerator;

    @Override
    public boolean passwordExists(Long userId, String password, int count) {
        if (count <= 0) {
            return false;
        }
        try (Page<SysUserPasswordHistory> page = PageMethod.startPage(1, count)) {
            LambdaQueryWrapper<SysUserPasswordHistory> qw = new LambdaQueryWrapper<>();
            qw.eq(SysUserPasswordHistory::getUserId, userId);
            qw.orderByDesc(SysUserPasswordHistory::getCreateTime);
            List<SysUserPasswordHistory> historyList = sysUserPasswordHistoryMapper.selectList(qw);
            return historyList.stream()
                    .anyMatch(history -> passwordEncoder.matches(password, history.getPassword()));
        }
    }

    @Override
    public void add(Long userId, String password) {
        SysUserPasswordHistory history = new SysUserPasswordHistory();
        history.setId(idGenerator.nextLongId());
        history.setUserId(userId);
        history.setPassword(password);
        history.setCreateTime(new Date());
        sysUserPasswordHistoryMapper.insert(history);
    }
} 